#include "stdafx.h"
#include "InstanceQuad.h"
#include "Camera2D.h"
#include <vector>

namespace a2d
{
//------------------------------------------------------------------

	GLsizei const VertexCount = 6;
	GLsizeiptr const PositionSize = VertexCount * sizeof(glm::vec2);
	glm::vec2 const PositionData[VertexCount] =
	{
		glm::vec2(-0.5f, -0.5f),
		glm::vec2(0.5f, -0.5f),
		glm::vec2(0.5f, 0.5f),
		glm::vec2(0.5f, 0.5f),
		glm::vec2(-0.5f, 0.5f),
		glm::vec2(-0.5f, -0.5f)
	};	
	GLsizeiptr const ColorSize = 2 * sizeof(glm::vec4);
	glm::vec4 const ColorData[2] =
	{
		glm::vec4(1.0f, 0.0f, 1.0f, 1.0f),
		glm::vec4(0.0f, 0.5f, 1.0f, 1.0f)
	};

	GLsizei const InstanceCount = 2;

	GLuint Color;

	VAO InstanceQuad::m_vao;
	ShaderProgram InstanceQuad::m_shaders;

	bool InstanceQuad::Create()
	{
		if ( !m_vao.Create() )
			return false;
		m_vao.Bind();
		if ( !m_shaders.Load("../instanced-array.vert", "../instanced-array.frag") )
			return false;

		m_vbo.Create();
		m_vbo.Bind();
		m_vbo.SetData(PositionSize, PositionData);
		m_vbo.ClearLocAtrib();
		m_vbo.SetOneVertexAtrib(2, 2);

		glVertexAttribDivisor(0, 0);

		m_pvw_mat = glGetUniformLocation(m_shaders.GetProgramID(), "MVPinst");
		
		glGenBuffers(1, &Color);
		glBindBuffer(GL_ARRAY_BUFFER, Color);
		glBufferData(GL_ARRAY_BUFFER, ColorSize, ColorData, GL_STATIC_DRAW);
		glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, 0);
		glVertexAttribDivisor(1, 1);
		glEnableVertexAttribArray(1);
		
		return true;
	}

	void InstanceQuad::Draw()
	{
		m_vao.Bind();
		//m_vbo.Bind();
		m_shaders.Bind();
		
		glm::mat4 Model[2];
		Model[0] = glm::translate(glm::mat4(1.0f), glm::vec3(-0.5f, 0.3f, 0.0f));
		Model[1] = glm::translate(glm::mat4(1.0f), glm::vec3(0.5f, -0.3f, 0.0f));
		glUniformMatrix4fv(m_pvw_mat, 2, GL_FALSE, &Model[0][0][0]);
				
		glDrawArraysInstanced(GL_TRIANGLES, 0, VertexCount, 2);
	}

	void InstanceQuad::Destroy()
	{

		m_vbo.Destroy();
		m_shaders.Destroy();
		m_vao.Destroy();
	}

//------------------------------------------------------------------
} // namespace a2d
